package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleConfigService;
import com.heima.article.service.ApArticleContentService;
import com.heima.article.service.ApArticleHtmlService;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 加载文章列表
     * @param loadType 加载类型 1-加载更多 2-加载更新
     * @param dto 参数
     * @return
     */
    @Override
    public ResponseResult load(Integer loadType, ArticleHomeDto dto) {
        List<ApArticle> apArticleList = apArticleMapper.load(loadType,dto);
        return ResponseResult.okResult(apArticleList);
    }

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult loadV2(Integer loadType, ArticleHomeDto dto, boolean isFromIndex) {

        //1.首页请求：优先从Redis中查询热点文章列表
        if(isFromIndex){
            //1.拼接RedisKey
            String redisKey = ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag();

            //2.从Redis查询热点文章列表JSON字符串
            String hotArticleVoListJSON = cacheService.get(redisKey);

            List<ApArticle> apArticleList = new ArrayList<>();

            //3.将JSON字符串转为文章列表
            List<ApArticle> apArticleHotList = JSON.parseArray(hotArticleVoListJSON, ApArticle.class);
            apArticleList.addAll(apArticleHotList);

            //4.如果文章列表不够30条，则剩余的从MySQL表中查询补全
            if(apArticleHotList.size()<30){
                dto.setSize(30-apArticleHotList.size());
                List<ApArticle> apArticleCommonList = apArticleMapper.load(loadType,dto);
                apArticleList.addAll(apArticleCommonList);
            }

            return ResponseResult.okResult(apArticleList);

        } else {
            //2.非首页请求：直接从MySQL查询文章列表
            return load(loadType,dto);
        }
    }

    @Autowired
    private ApArticleConfigService apArticleConfigService;

    @Autowired
    private ApArticleContentService apArticleContentService;

    @Autowired
    private ApArticleHtmlService apArticleHtmlService;

    @GlobalTransactional
    @Override
    public ResponseResult saveOrUpdateArticle(ArticleDto dto) {

        //1.判断必要参数是否为空
        if(StringUtils.isBlank(dto.getTitle()) || StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.复制dto给pojo
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

        //3.id无值，创建APP文章
        if(apArticle.getId()==null){

            //创建ap_article数据
            this.save(apArticle);

            //创建ap_article_config数据
            ApArticleConfig config = new ApArticleConfig();
            config.setArticleId(apArticle.getId());
            config.setIsForward(true);//允许转发
            config.setIsComment(true);//允许评论
            config.setIsDown(false);//未下架
            config.setIsDelete(false);//未删除
            apArticleConfigService.save(config);

            //创建ap_article_content数据
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(apArticle.getId());
            content.setContent(dto.getContent());//内容
            apArticleContentService.save(content);

        } else {
            //4.id有值，更新APP文章

            //更新ap_article数据
            Integer articleCount = this.lambdaQuery().eq(ApArticle::getId, apArticle.getId()).count();
            if(articleCount==0){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
            }

            this.updateById(apArticle);

            //更新ap_article_content数据

            //select count(*) from ap_article_conent where article_id=?
            Integer contentCount = apArticleContentService.lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()).count();
            if(contentCount==0){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "内容不存在");
            }

            //update ap_article_conent set content=? where article_id=?
            apArticleContentService.lambdaUpdate()
                    .eq(ApArticleContent::getArticleId, apArticle.getId()) //更新条件
                    .set(ApArticleContent::getContent,dto.getContent())//更新的数据
                    .update();
        }

        //5.异步生成文章页（使用ThreaddPool技术完成）
        apArticleHtmlService.generateHtml(apArticle.getId(),dto.getContent());

        //6.响应文章主键ID
        return ResponseResult.okResult(apArticle.getId());
    }


}
